//
//  HMEmoticonPageCell.swift
//  WeiBo14
//
//  Created by HM on 16/3/12.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

class HMEmoticonPageCell: UICollectionViewCell {
    
    // 当前cell显示的表情数组.供外界设置
    var emoticons: [HMEmoticon]? {
        didSet{
            
            // 首先将所有的按钮隐藏
            for value in emoticonButtons {
                value.hidden = true
            }
            
            // 给当前cell身上的表情按钮填充数据
            for (index,emoticon) in emoticons!.enumerate() {
                
                // 1. 取到按钮
                let button = emoticonButtons[index]
                button.hidden = false
                // 给按钮设置模型数据
                button.emoticon = emoticon
                
            }
        }
    }
    
    /// 装表情按钮的集合
    private lazy var emoticonButtons: [HMEmoticonButton] = [HMEmoticonButton]()
    
    var indexPath: NSIndexPath? {
        didSet{
            //label.text = "第\(indexPath!.section)组,第\(indexPath!.item)页"
            recentLabel.hidden = indexPath?.section != 0
        }
    }
    
    // MARK: - 设置界面
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        contentView.addSubview(recentLabel)

        recentLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-8)
        }
        // 添加表情按钮
        addEmoticonButtons()
        contentView.addSubview(deleteButton)
        
        // 添加长按手势
        let ges = UILongPressGestureRecognizer(target: self, action: "longPress:")
        self.addGestureRecognizer(ges)
    }
    
    
    /// 添加20个表情按钮
    private func addEmoticonButtons(){
        
        // 遍历添加表情按钮
        for _ in 0..<HMEmoticonsPageCount {
            let button = HMEmoticonButton()
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            contentView.addSubview(button)
            // 设置文字大小
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
            // 将表情按钮添加到数组里面去,以便在下面取到表情按钮调整位置
            emoticonButtons.append(button)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算每一个表情按钮的宽高
        let itemW = self.frame.width / 7
        let itemH = (self.frame.height - 20) / 3
        
        // 布局子控件
        // 计算20个表情按钮的位置
        for (index,button) in emoticonButtons.enumerate() {
            
            // 计算出该按钮是在第几列第几行
            let col = index % 7
            let row = index / 7
            
            // 计算按钮的位置
            button.frame.origin.x = CGFloat(col) * itemW
            button.frame.origin.y = CGFloat(row) * itemH
            
            // 设置按钮大小
            button.frame.size = CGSize(width: itemW, height: itemH)
        }
        // 设置删除按钮的位置
        deleteButton.frame.origin = CGPoint(x: self.frame.width - itemW, y: itemH * 2)
        // 设置大小
        deleteButton.frame.size = CGSize(width: itemW, height: itemH)
        
        
    }
    
    // MARK: - 监听事件
    
    /// 长按所触发的方法
    ///
    /// - parameter ges: <#ges description#>
    @objc private func longPress(ges: UIGestureRecognizer) {
        print("长按手势触发了")
        
        /// 通过传入一个位置,返回该位置对应的按钮
        ///
        /// - parameter location: <#location description#>
        ///
        /// - returns: <#return value description#>
        func buttonWithLocation(location: CGPoint) -> HMEmoticonButton? {
            
            // 遍历按钮,查看哪一个按钮的范围包含location
            for value in emoticonButtons {
                // 判断location是否是value.frame的范围内
                if CGRectContainsPoint(value.frame, location) {
                    return value
                }
            }
            return nil
        }
        
        // 1. 取到手指所在的点
        let location = ges.locationInView(self)
        // 2. 取到点所对应的表情按钮
        guard let button = buttonWithLocation(location) where button.hidden == false else {
            popView.removeFromSuperview()
            return
        }
        // 3. 弹出popView并设置数据
        
        switch ges.state {
        case .Began,.Changed:
            // 取到最后一个window
            let window = UIApplication.sharedApplication().windows.last!
            // 添加到window
            window.addSubview(popView)
            
            // 调整位置
            let rect = button.superview!.convertRect(button.frame, toView: window)
            
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            // 设置数据
            popView.emoticonButton.emoticon = button.emoticon
        default:
            popView.removeFromSuperview()
        }
        
        
        
        
    }
    
    /// 删除按钮要执行的方法
    @objc private func deleteButtonClick(){
        print("删除按钮点击了")
            //  发送删除按钮点击的通知
        NSNotificationCenter.defaultCenter().postNotificationName(HMKeyboardDelDidSelectedNotification, object: nil)
    }
    
    /// 表情按钮点击执行的方法
    ///
    /// - parameter button: <#button description#>
    @objc private func emoticonButtonClick(button: HMEmoticonButton) {
        
        // 保存表情到最近表情
        HMEmoticonTools.sharedTools.saveRecentEmoticon(button.emoticon!)
        
        // 发送表情点击的通知,并且将表情按钮对应的表情模型通过userInfo传到接收者那儿
        NSNotificationCenter.defaultCenter().postNotificationName(HMEmoticonDidSelectedNotification, object: nil, userInfo: ["emoticon": button.emoticon!])
        
        let popView = HMEmoticonPopView.popView()
        
        // 把popView加到最上层,取到最上层的window
        let window = UIApplication.sharedApplication().windows.last!
        window.addSubview(popView)
        // 按钮相对于 window 上的位置 重点
        
        // _.converRect(_, toView:_)
        let rect = button.convertRect(button.bounds, toView: window)
//        let rect = button.superView.convertRect(button.frame, toView: window)
        // 设置frame
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        // 设置数据
        popView.emoticonButton.emoticon = button.emoticon
        // 过0.25秒之后消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
    }
    
    // MARK: - 懒加载控件
    
    private lazy var popView: HMEmoticonPopView = {
        let popView = HMEmoticonPopView.popView()
        return popView
    }()
    
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置不同状态的图片
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        return button
    }()
    
    // 测试使用
    private lazy var recentLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 12)
        label.text = "最近使用的表情"
        return label
    }()
}
